package com.changgou.pay.service.impl;

import com.changgou.pay.service.WxPayService;
import com.github.wxpay.sdk.WXPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class WxPayServiceImpl implements WxPayService {

    @Autowired
    private WXPay wxPay;
    @Autowired
    private WxPayService wxPayService;

    @Value("${wxpay.notify_url}")
    private String notify_url;

    /***
     * 微信下单
     * @param orderId
     * @param money
     * @return
     */
    @Override
    public Map<String, String> nativePay(String orderId, Integer money) {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("body", "畅购");//商品描述
            map.put("out_trade_no", orderId);//内部订单号 orderId

            //涉及到钱,不能用double float 损失精度 要使用 BigDecimal 不会损失精度
            //BigDecimal进行计算的时候:数字和运算都要用BigDecimal带的类型和方法 0.01 * 100
            BigDecimal payMoney = new BigDecimal("0.01");
            BigDecimal fen = payMoney.multiply(new BigDecimal("100"));//1.00
            fen = fen.setScale(0, BigDecimal.ROUND_UP);//1 向上取整
            map.put("total_fee", String.valueOf(fen));

            map.put("spbill_create_ip", "127.0.0.1");//用户ip
            map.put("notify_url", notify_url);//通知地址
            map.put("trade_type", "NATIVE");//支付类型

            Map<String, String> result = wxPay.unifiedOrder(map);//下单
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /***
     * 查询订单
     * @param orderId
     * @return
     */
    @Override
    public Map<String, String> queryOrder(String orderId) {
        try {
            Map<String, String> reqData = new HashMap();
            reqData.put("out_trade_no", orderId);

            Map<String, String> map = wxPay.orderQuery(reqData);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /***
     * 关闭微信订单
     * @param orderId
     * @return
     */
    @Override
    public Map<String, String> closeOrder(String orderId) {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("out_trade_no", orderId);
            Map<String, String> resultMap = wxPay.closeOrder(map);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
